package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.AuditClaimMapper;
import com.xmy.cultivate.mapper.AuditFlowDetailMapper;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.respons.FlowDetailRs;
import com.xmy.cultivate.respons.FlowRs;
import com.xmy.cultivate.respons.FlowTeacherRs;
import com.xmy.cultivate.respons.QyWeChartPushRs;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 实例审批流程 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-01-01
 */
@Service
public class AuditFlowDetailServiceImpl extends ServiceImpl<AuditFlowDetailMapper, AuditFlowDetail> implements IAuditFlowDetailService {

    @Autowired
    AuditClaimMapper auditClaimMapper;

    @Autowired
    AuditFlowDetailMapper auditFlowDetailMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IAuditFlowService iAuditFlowService;

    @Autowired
    IAuditReturnPremiumService iAuditReturnPremiumService;

    @Autowired
    IStaffService iStaffService;


    @Override
    public FlowDetailRs getFlowDetailBySourseId(Long sourseId) {
        AuditClaim auditClaim = auditClaimMapper.getClaimOneByIdDesc(sourseId);
        List<AuditFlowDetail> auditFlowDetailList = auditFlowDetailMapper.getFlowDetailForSourseId(sourseId,auditClaim.getVersionNum());
        List<FlowRs> flowRsList = new ArrayList<>();
        List<String> stayCheckNameList = new ArrayList<>();
        List<Long> stayCheckIdList = new ArrayList<>();
        for (AuditFlowDetail auditFlowDetail : auditFlowDetailList) {
            FlowRs flowRs = new FlowRs();
            flowRs.setId(auditFlowDetail.getId());
            flowRs.setName(auditFlowDetail.getName());
            flowRs.setType(auditFlowDetail.getType());
            flowRs.setStepNum(auditFlowDetail.getStepNum());

            //一个人审核不通过，显示不通过
            if (auditFlowDetail.getStatusStr().contains("2")){
                flowRs.setStatus(2);
            }else if (auditFlowDetail.getStepNum() < auditClaim.getStepNum() || (auditFlowDetail.getStepNum() == auditClaim.getStepNum() && auditFlowDetail.getStatusStr().contains("1") && !auditFlowDetail.getStatusStr().contains("0"))){
                //审核步数已过，表示已审核通过，或者步数相等并且有审核通过，并且没有未审核的
                flowRs.setStatus(1);
            } else if (auditFlowDetail.getStepNum() == auditClaim.getStepNum() && auditFlowDetail.getStatusStr().contains("0")) {
                //审核频数相等，并且有未审核的，为审核中
                flowRs.setStatus(3);
            } else {
                //0为未审核，还未到审核
                flowRs.setStatus(0);
            }

            if (auditFlowDetail.getCheckIds()!=null){
                List<String> checkIdList = Arrays.asList(auditFlowDetail.getCheckIds().split(","));
                List<String> statusList = Arrays.asList(auditFlowDetail.getStatusStr().split(","));

                List<FlowTeacherRs> flowTeacherRsList = new ArrayList<>();
                Integer i = 0;
                for (String str :checkIdList){
                    //System.out.println("str:"+str);
                    Staff staff = staffMapper.selectById(Long.parseLong(str));
                    if (staff!=null){
                        FlowTeacherRs flowTeacherRs = new FlowTeacherRs();
                        flowTeacherRs.setId(staff.getId());
                        flowTeacherRs.setName(staff.getName());
                        flowTeacherRs.setStatus(Integer.parseInt(statusList.get(i)));
                        flowTeacherRsList.add(flowTeacherRs);
                        //待审批人
                        if (flowRs.getStatus().equals(3) && statusList.get(i).equals("0")){
                            stayCheckNameList.add(staff.getName());
                            stayCheckIdList.add(staff.getId());
                        }
                    }
                    i++;
                }
                //List<FlowTeacherRs> flowTeacherRsList = staffMapper.getFlowTeacherList(auditFlowDetail.getCheckIds());
                flowRs.setTeacherList(flowTeacherRsList);
            }
            flowRsList.add(flowRs);
        }
        FlowDetailRs flowDetailRs = new FlowDetailRs();
        flowDetailRs.setFlowRsList(flowRsList);
        flowDetailRs.setStayCheckIdList(stayCheckIdList);
        flowDetailRs.setStayCheckNameList(stayCheckNameList);

        return flowDetailRs;
    }


    /**
     * 发送当前步骤的提醒提醒
     * @param claimId
     * @return
     */
    @Override
    public boolean sendRemind(Long claimId, Integer nowStep) {
        AuditClaim auditClaim = auditClaimMapper.selectById(claimId);
        if (!Objects.isNull(auditClaim)){
            //下一个审批人
            QueryWrapper<AuditFlowDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("flow_id", auditClaim.getFlowId());
            queryWrapper.eq("sourse_id", auditClaim.getId());
            queryWrapper.eq("sourse_version_num", auditClaim.getVersionNum());
            queryWrapper.eq("step_num", auditClaim.getStepNum());
            List<AuditFlowDetail> auditFlowDetailList = auditFlowDetailMapper.selectList(queryWrapper);
            for (AuditFlowDetail auditFlowDetail : auditFlowDetailList) {
                if (auditFlowDetail.getType().equals(1)){//审核类型
                    if (auditFlowDetail.getStatus().equals(0) && auditFlowDetail.getIsArrive().equals(1)){
                        QyWeChartPushRs qyWeChartPushRs = getPushMsg(auditClaim,auditFlowDetail.getStepNum(),1);
                        if (!Objects.isNull(qyWeChartPushRs)){
                            Staff staff = iStaffService.getById(auditFlowDetail.getCheckId());
                            if (!Objects.isNull(staff)){
                                if (StringUtils.isNotBlank(staff.getQyWecharId())){
                                    qyWeChartPushRs.setToUser(staff.getQyWecharId());
                                    //推送到企业微信
                                    iMqPushService.pushContentForQyWeChar(qyWeChartPushRs);
                                }
                            }
                        }
                    }
                }
            }
            //抄送
            List<AuditFlowDetail> auditFlowDetailListCopy = this.getCopyFlowDetailList(claimId,auditClaim.getVersionNum(),2,1);
            for (AuditFlowDetail auditFlowDetail : auditFlowDetailListCopy) {
                if (auditFlowDetail.getType().equals(1)){//审核类型
                    if (auditFlowDetail.getStatus().equals(0) && auditFlowDetail.getIsArrive().equals(1)){
                        QyWeChartPushRs qyWeChartPushRs = getPushMsg(auditClaim,auditFlowDetail.getStepNum(),2);
                        if (!Objects.isNull(qyWeChartPushRs)){
                            Staff staff = iStaffService.getById(auditFlowDetail.getCheckId());
                            if (!Objects.isNull(staff)){
                                if (StringUtils.isNotBlank(staff.getQyWecharId())){
                                    qyWeChartPushRs.setToUser(staff.getQyWecharId());
                                    //推送到企业微信
                                    iMqPushService.pushContentForQyWeChar(qyWeChartPushRs);
                                }
                            }
                        }
                    }
                }
            }

        }


        return true;
    }

    /**
     *
     * @param auditClaim
     * @param nowStep
     * @param type 1审批，2抄送
     * @return
     */
    public QyWeChartPushRs getPushMsg(AuditClaim auditClaim,Integer nowStep,Integer type) {
        AuditFlow auditFlow = iAuditFlowService.getById(auditClaim.getFlowId());

        String dateTime = LocalDateTime.now().withNano(0).toString();
        dateTime = dateTime.replace('T', ' ');

        QyWeChartPushRs qyWeChartPushRs = null;
        if (!Objects.isNull(auditFlow)) {
            if (auditFlow.getId().equals(1568138350324350902L)) {
                String content = auditClaim.getPushMsg();
                qyWeChartPushRs = new QyWeChartPushRs();
                StringBuilder titleBuilder = new StringBuilder();
                titleBuilder.append(auditFlow.getName());
                if (type.equals(1)){
                    if (nowStep.equals(1)){
                        titleBuilder.append("待确认");
                    }else if (nowStep.equals(2)){
                        titleBuilder.append("待转帐");
                    }
                }else {
                    titleBuilder.append("已转帐");
                }
                qyWeChartPushRs.setTitle(titleBuilder.toString());
                qyWeChartPushRs.setDateTime(dateTime);
                qyWeChartPushRs.setContent(content);
                qyWeChartPushRs.setLinkUrl("http://teacher.5ixmy.xyz/#/pages/webview/index");
                qyWeChartPushRs.setRemark("请尽快处理");
            }
        }
        return qyWeChartPushRs;
    }

    @Override
    public AuditFlowDetail getNowStepFlowDetail(Long sourseId,
                                                Integer sourseVersionNum,
                                                Integer nowStepNum,
                                                Integer type){
        return auditFlowDetailMapper.getNowStepFlowDetail(sourseId,sourseVersionNum,nowStepNum,type);
    }

    @Override
    public List<AuditFlowDetail> getCopyFlowDetailList(Long sourseId,
                                                       Integer sourseVersionNum,
                                                       Integer type,
                                                       Integer isArrive){
        return auditFlowDetailMapper.getCopyFlowDetailList(sourseId,sourseVersionNum,type,isArrive);
    }
}
